/*
## 默认
- 不升音
- 第一个8度
## 学习中遇到的问题：
- ERROR L107: ADDRESS SPACE OVERFLOW
    > 内存空间溢出，改target里的编译模式
- error C249: 'DATA': SEGMENT TOO LARGE
    > 数组前没加code
*/
#include<reg51.h>
#define FREQ 12000000
#define SPEED 100
#define keyTune P1

sbit SPEAKER = P2^0;
unsigned int num = 0;
unsigned char tune_TH, tune_TL;

unsigned char dura_TH, dura_TL;

unsigned char duration = 0x08;




unsigned char code music_freq_tab[32] = {
    0xff,0xea,//第0个8度
    256-FREQ/24/131/256, 256-FREQ/24/131%256,
    256-FREQ/24/147/256, 256-FREQ/24/147%256,
    256-FREQ/24/165/256, 256-FREQ/24/165%256,
    256-FREQ/24/175/256, 256-FREQ/24/175%256,
    256-FREQ/24/196/256, 256-FREQ/24/196%256,
    256-FREQ/24/221/256, 256-FREQ/24/221%256,
    256-FREQ/24/248/256, 256-FREQ/24/248%256,

    0xff,0xea,
    256-FREQ/24/262/256, 256-FREQ/24/262%256,
    256-FREQ/24/294/256, 256-FREQ/24/294%256,
    256-FREQ/24/330/256, 256-FREQ/24/330%256,
    256-FREQ/24/350/256, 256-FREQ/24/350%256,
    256-FREQ/24/393/256, 256-FREQ/24/393%256,
    256-FREQ/24/441/256, 256-FREQ/24/441%256,
    256-FREQ/24/495/256, 256-FREQ/24/495%256,
};

void delay(unsigned int);
void music_play();

void main()
{
    TMOD = 0x11;
    EA = 1;
    ET0 = 1;
    ET1 = 1;
    TR0 = 0;
    TR1 = 0;
    while(1){
        switch (keyTune)
        {
        case 0xfe://1
            num = 17;
            break;
        case 0xfd://2
            num = 19;
            break;
        case 0xfb://3
            num = 21;
            break;
        case 0xf7://4
            num = 23;
            break;
        case 0xef://5
            num = 25;
            break;
        case 0xdf://6
            num = 27;
            break;
        case 0xbf://7
            num = 29;
            break;
        case 0x7f://1`
            num = 31;
            break;
        } 
        if (num)
        {
            music_play();
            delay(2000);
        }
        
    }
}

void delay(unsigned int ms)
{
    unsigned char i,j;
    while(ms--)
    {
        for (i = 0; i < 2; i++)
        {
            for(j = 0; j<122; j++);
        }
    }
}

void decoding(unsigned int n){
    tune_TH = music_freq_tab[n];
    tune_TH = music_freq_tab[n+1];
    dura_TH = (65536-duration*1000)/256;
    dura_TL = (65536-duration*1000)%256;
}

void music_play()
{
    TH1 = 0xff;
    TL1 = 0xff;
    TR1 = 1;
    TR0 = 0; 
    TR1 = 0;
    SPEAKER = 0;
    num = 0;
}

void music_tune() interrupt 1
{
    SPEAKER = ~SPEAKER;
    TH0 = tune_TH;
    TL0 = tune_TL;
    num = 0;
}

void music_dura() interrupt 3
{
    decoding(num);
    TH0 = tune_TH;
    TL0 = tune_TL;
    TR0 =1;
    TH1 = dura_TH;
    TL1 = dura_TL;
    num = 0;
}

